package com.siyoumi.mybatispuls;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.util.XStr;
import lombok.Getter;
import lombok.Setter;

public class JoinWrapperPlus<T>
        extends QueryWrapper<T> {
    @Setter
    private StringBuilder sqlJoin = new StringBuilder();

    /**
     * SELECT * FROM TABLE AS tableAs
     */
    @Setter
    private String as;


    public JoinWrapperPlus<T> leftJoin(String tableName, String first, String second) {
        return leftJoin(tableName, first, second, "");
    }

    public JoinWrapperPlus<T> leftJoin(String tableName, String first, String second, String where, Object... values) {
        return join(tableName, first, second, " LEFT JOIN ", where, values);
    }

    public JoinWrapperPlus<T> join(String tableName, String first, String second) {
        return join(tableName, first, second, " JOIN ", "");
    }

    /**
     * @param tableName
     * @param first
     * @param second
     * @param join
     * @param where
     * @param values
     */
    protected JoinWrapperPlus<T> join(String tableName, String first, String second, String join, String where, Object... values) {
        String str = XStr.concat(join, " ", tableName, " ON ", first, " = ", second, " ", where);
        //sql生成动态参数
        String sql = formatSqlMaybeWithParam(str, "", values);

        sqlJoin.append(sql);
        return this;
    }

    public String getJoinSql() {
        String sql = sqlJoin.toString();
        if (XStr.hasAnyText(as)) {
            sql = XStr.concat(" AS ", as, " ", sql);
        }

        return sql;
    }


    public JoinWrapperPlus<T> cloneJoinPlus() {
        JoinWrapperPlus<T> query = (JoinWrapperPlus<T>) super.clone();
        query.setAs(as);
        query.setSqlJoin(sqlJoin);
        return query;
    }
}
